﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Core.Infrastructure.CommandExtensions
{
    public class TextAreaKeyEnter
    {
        private static readonly DependencyProperty TextAreaKeyEnterCommandBehaviorProperty = DependencyProperty.RegisterAttached(
            "TextAreaKeyEnterCommandBehavior",
            typeof(TextAreaKeyEnterCommandBehavior),
            typeof(TextAreaKeyEnter),
            null);

        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(TextAreaKeyEnter),
            new PropertyMetadata(OnSetCommandCallback));

        public static void SetCommand(TextBox textBox, ICommand command)
        {
            textBox.SetValue(CommandProperty, command);
        }

        public static ICommand GetCommand(TextBox textBox)
        {
            return textBox.GetValue(CommandProperty) as ICommand;
        }

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var textBox = dependencyObject as TextBox;
            if (textBox != null)
                GetOrCreateBehavior(textBox).Command = e.NewValue as ICommand;
        }

        private static TextAreaKeyEnterCommandBehavior GetOrCreateBehavior(TextBox textBox)
        {
            var behavior = textBox.GetValue(TextAreaKeyEnterCommandBehaviorProperty) as TextAreaKeyEnterCommandBehavior;
            if (behavior == null)
            {
                behavior = new TextAreaKeyEnterCommandBehavior(textBox);
                textBox.SetValue(TextAreaKeyEnterCommandBehaviorProperty, behavior);
            }

            return behavior;
        }
    }
}
